/*
 *  Copyright 1999-2019 Seata.io Group.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.auditlog.datasource.execute;

import com.auditlog.datasource.StatementProxy;
import com.auditlog.datasource.db.SqlType;
import com.auditlog.datasource.struct.SqlMeta;
import com.auditlog.sql.parser.CachedSqlParser;

import java.sql.SQLException;
import java.sql.Statement;

/**
 * The type Execute template.
 *
 * @author sharajava
 */
public class ExecuteTemplate {

    /**
     * Execute t.
     *
     * @param <T>               the type parameter
     * @param <S>               the type parameter
     * @param statementProxy    the statement proxy
     * @param statementCallback the statement callback
     * @param args              the args
     * @return the t
     * @throws SQLException the sql exception
     */
    public static <T, S extends Statement> T execute(StatementProxy<S> statementProxy,
                                                     StatementCallback<T, S> statementCallback,
                                                     Object... args) throws SQLException {
        String targetSQL = statementProxy.getTargetSQL();
        SqlMeta sqlMeta = CachedSqlParser.parse(targetSQL);
        SqlType sqlType = sqlMeta.getSqlType();
        if (sqlType == SqlType.EXCEPTION) {
            throw new SQLException("sql解析异常");
        }
        Executor<T> executor;
        if (sqlType == SqlType.MULTI) {
            executor = new MultiExecutor(statementProxy, statementCallback, sqlMeta);
        } else {
            executor = new SingleExecutor(statementProxy, statementCallback, sqlMeta);
        }
        T rs;
        try {
            // 对于自动提交事务，执行完业务后事务已提交
            rs = executor.execute(args);
        } catch (Throwable ex) {
            if (!(ex instanceof SQLException)) {
                ex = new SQLException(ex);
            }
            throw (SQLException) ex;
        }
        return rs;
    }
}
